<template>
  <div id="pdf-view">
    <canvas v-for="page in state.pdfPages" :key="page" :id="`page-${page}`"></canvas>
    <div id="text-view"></div>
  </div>
</template>

<script setup>
import { reactive, onMounted, nextTick } from 'vue'
// import * as pdfjsViewer from 'pdfjs-dist/web/pdf_viewer.js'
import 'pdfjs-dist/web/pdf_viewer.css'
import * as PDF from 'pdfjs-dist'
// import { PDFDocumentProxy } from 'pdfjs-dist'

// 从父组件传入的参数
const props = defineProps({
  pdfUrl: {
    type: String,
    required: true,
  },
})

// const baseUrl = import.meta.env.VITE_BASE_URL

PDF.GlobalWorkerOptions.workerSrc = '/pdf/build/pdf.worker.min.mjs'
const cMapUrl = '/pdf/cmaps/'

// const eventBus = new pdfjsViewer.EventBus();

const state = reactive({
  // 文件路径
  pdfPath: props.pdfUrl,
  // 总页数
  pdfPages: 1,
  // 页面缩放
  pdfScale: 2,
})

onMounted(() => {
  loadFile(state.pdfPath)
})

let pdfDoc = null

function loadFile(url) {
  PDF.getDocument({
    url,
    cMapUrl: cMapUrl,
    cMapPacked: true,
  }).promise.then((pdf) => {
    pdfDoc = pdf
    // 获取pdf文件总页数
    state.pdfPages = pdf.numPages
    nextTick(() => {
      renderPage(1) // 从第一页开始渲染
    })
  })
}

function renderPage(num) {
  pdfDoc.getPage(num).then((page) => {
    // 绑定 id 值对应的元素
    const canvas = document.getElementById(`page-${num}`)
    const ctx = canvas.getContext('2d')
    const viewport = page.getViewport({ scale: state.pdfScale })
    canvas.width = viewport.width
    canvas.height = viewport.height
    const renderContext = {
      canvasContext: ctx,
      viewport,
    }
    page.render(renderContext)
    // state.pdfPages 为 pdf 文件总页数
    if (num < state.pdfPages) {
      renderPage(num + 1)
    }
  })
}
</script>
